strchr関数とstrrchr関数は、文字列中から指定された文字を検索します。strchr関数とstrrchr関数の相違は、strchr関数は文字列の先頭から検索を開始するのに対して、strrchr関数は文字列の最後から開始します。従って、strchr関数は最初に現れた文字を検索し、strrchr関数は最後に現れた文字を検索します。
#include <string.h>
char *strchr(const char *s, int c);
char *strrchr(const char *s, int c);
*sは検索対象文字列を指定します。
cは検索する文字を指定します。
戻り値として、検索できた場合は検索した文字のアドレスを返します。検索できなかった場合はNULLを返します。
プログラム 例
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 1024
int main()
{
FILE *fp;
char path[50];
char key;
char buff[SIZE];
char *buff_ptr;
int key_cnt;
printf('ファイルのパス名を入力してください ==> ');
scanf('%s%*c', path);
if ((fp = fopen(path, 'r')) == NULL) {
fprintf(stderr, '%sのオープンができませんでした\n', path);
exit(EXIT_FAILURE);
}
printf('検索する文字を入力してください ==> ');
scanf('%c%*c', &key);
key_cnt = 0;
while(fgets(buff, SIZE, fp) != NULL) {
buff_ptr = buff;
while (*buff_ptr) {
if ((buff_ptr = strchr(buff_ptr, key)) != NULL) {
++key_cnt;
++buff_ptr;
}
else {
break;
}
}
}
fclose(fp);
printf('%sファイルには%cが%d個ありました\n', path, key, key_cnt);
return EXIT_SUCCESS;
}
例の実行結果
$ cat temp.txt
#include <stdio.h>
int main()
{
printf('Hello World!!.\n');
return 0;
}
$
$ ./strchr.exe
ファイルのパス名を入力してください ==> temp.txt
検索する文字を入力してください ==> i
temp.txtファイルにはiが5個ありました
$
$ ./strchr.exe
ファイルのパス名を入力してください ==> temp.txt
検索する文字を入力してください ==> !
temp.txtファイルには!が2個ありました
$